const request = require('request')
const Promise = require('bluebird')
const fs = require('fs').promises
const path = require('path')
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

function myRequestGet (url) {
  return new Promise((resolve, reject) => {
    request({
      url: url,
      headers: {
        strictSSL: false, // allow us to use our self-signed cert for testing
        rejectUnauthorized: false
      }
    }, (err, res) => {
      if (err) {
        reject(err)
      } else {
        resolve(res)
      }
    })
  })
}
async function getOnePackage (series, pack, callback, result) {
  try {
    let url = `https://www.qi-wmcard.com/series/${series}/pack/${pack}/page/`
    let pageNum = 1, tag = true
    while (tag) {
      tag = await getData(url + pageNum, callback, result)
      if (pageNum === 1 && tag === 0) {
        throw new Error('emptyPorS')
      }
      if (tag < 10) {
        tag = false
      }
      pageNum += 1
    }
  } catch (error) {
    throw error
  }
}
async function getData (url, callback, result) {
  let codeList = []
  try {
    let ListPage = await myRequestGet(url)
    ListPage = JSON.stringify(ListPage)
    //获取当前页面所有编号,理论值最大为10个
    for (let i = 1; i < 20; i++) {
      cardCode = getCardCode_list(ListPage, i)
      if (cardCode) {
        //整理列表页的数据
        codeList.push({
          url: getCardPictUrl_list(ListPage, i),
          code: cardCode,
          package: getCardPackage_list(ListPage, i)
        })
      } else {
        break
      }
    }
  } catch (error) {
    throw error
  }
  //便利数组
  Promise.mapSeries(codeList, async (item, key) => {
    let urlDetail = `https://www.qi-wmcard.com/card/${item.code}`
    let detailPage = await myRequestGet(urlDetail)
    detailPage = JSON.stringify(detailPage).split('本站提供的卡片图片')[1]
    let _result = getAllMsgFromDetail(codeList[key], JSON.stringify(detailPage))
    callback && callback(_result, result)
  })
  return codeList.length
}


//卡片编号(通过该方法获得列表页的编号,拼接地址,进行查询,唯二在列表页进行的爬取)
function getCardCode_list (string, i) {
  return string.split('卡片编号')[i]?.split('<td>\\n')[1]?.split('</td>\\n')[0].trim()
}
//卡包
function getCardPackage_list (string, i) {
  // let temp = string.split('收录卡包')[i].split('">')[1].split('</a>')[0].trim()
  // console.log(temp);
  return {
    packageCycle: string.split('收录卡包')[i].split('">')[1].split('</a>')[0].trim(),
    packageDetail: string.split('收录卡包')[i].split('">')[2].split('</a>')[0].trim(),
  }
}
//地址
function getCardPictUrl_list (string, i) {
  return 'https://www.qi-wmcard.com' + string.split('height=\\"120px\\"\\n')[i].split('src=\\\"')[1].split('\\\"')[0]
}
//三文名
function getCardName (string) {
  return {
    cnName: string.split('">中文名称')[1].split('colspan=\\\\\\\"3\\\\\\\">\\\\n')[1].split('</td>')[0].replace(/·/g, "\\·").trim(),
    enName: string.split('">英文名称')[1].split('colspan=\\\\\\\"3\\\\\\\">\\\\n')[1].split('</td>')[0].replace(/·/g, "\\·").trim(),
    jpName: string.split('">日文名称')[1].split('colspan=\\\\\\\"3\\\\\\\">\\\\n')[1].split('</td>')[0].replace(/·/g, "\\·").trim(),
  }
}
//密码
function getCardPassword (string) {
  return string.split('">卡片密码')[1].split('colspan=')[1].split('n')[1].split('</td>')[0].trim()
}
//类型
function getCardType (string) {
  let temp = string.split('">卡片种类')[1].split('colspan=')[1]
  let typeOne = temp.split("\\n")[1]
    , typeTwo = temp.split("\\n")[1]?.split(';')[1]?.split('</td>')[0].replace(/\s/g, '')
  return {
    typeOne: typeTwo ? typeOne.split('\/&')[0].replace(/\s/g, '').replace(/\&nbsp;/g, '').replace('\\', '') : typeOne.split('</td>')[0].replace(/\s/g, '').replace('\&nbsp;', '').replace('\\\\', ''),
    typeTwo: typeTwo ? typeTwo.replace('\&nbsp', '') : '-'
  }
}
//属性
function getCardAttribute (string) {
  return string.split('">属性')[1].split('colspan=')[1]?.split('n')[1]?.split('</td>')[0].trim() || ''
}
//种族
function getCardRace (string) {
  return string.split('">种族')[1].split('colspan=')[1]?.split('n')[1]?.split('</td>')[0].trim() || ''
}
//星级
function getCardRank (string) {
  return string.split('">星')[1]?.split('n')[5]?.split('</td>')[0].trim() || ''
}
//攻击防御
function getCardAtkAndDef (string) {
  return {
    attack: string.split('">攻击力')[1]?.split('n')[5]?.split('</td>')[0].trim() || '',
    defense: string.split('">防御力')[1]?.split('n')[5]?.split('</td>')[0].trim() || '',
  }
}
//稀有度rare
function getCardRare (string) {
  return string.split('">稀有度')[1].split('colspan=\\\\\\"3\\\\\\">\\\\n')[1].split('</td>')[0].trim()
}
//使用性 usability
function getCardUsability (string) {
  return {
    OCG: string.split('OCG')[1].split(';')[1].split('&')[0],
    TCG: string.split('TCG')[1].split(';')[1].split('&')[0],
    TCOCG: string.split('TCOCG')[1].split(';')[1].split('</td>')[0].trim(),
  }
}
//效果
function getCardEffect (string) {
  let temp = string.split('<table border=\\\\\\"1\\\\\\" cellspacing=\\\\\\"0\\\\\\" cellpadding=\\\\\\"10\\\\\\" width=\\\\\\"720px\\\\\\">')
  // console.log(temp);
  return {
    cnEffect: temp[1].split('<td>\\\\n')[1].split('</td>')[0].replace(/\\\\r<br\/>/g, '').trim(),
    jpEffect: temp[2].split('<td style=\\\\\\"font-family: MS PGothic;\\\\\\">\\\\n')[1].split('</td>')[0].replace(/\\\\r<br\/>/g, '').trim(),
    enEffect: temp[3].split('<td>\\\\n')[1].split('</td>')[0].replace(/\\\\r<br\/>/g, '').trim(),
  }
}
function getAllMsgFromDetail (dataFromList, string) {

  return {
    ...dataFromList,
    name: getCardName(string),
    password: getCardPassword(string),
    type: getCardType(string),
    attribute: getCardAttribute(string),
    race: getCardRace(string),
    rank: getCardRank(string),
    atkAndDef: getCardAtkAndDef(string),
    rare: getCardRare(string),
    usability: getCardUsability(string),
    effect: getCardEffect(string),
  }
}

module.exports = {
  getOnePackage, getData
}